package com.src.xyzk_personal.config;

import java.util.List;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.util.Log;

public class WifiAdmin {
    public static final String TAG = "WifiAdmin";
    private WifiManager m_wifimanger = null;	//定义wifimanger对象
    private WifiInfo m_wifiinfo = null;
    private List<ScanResult> m_wifilist = null;	//扫描的网络连接列表
    private List<WifiConfiguration> m_wifi_config = null;	//网络连接列表
    private WifiLock m_wifilock;
    private WifiConfiguration m_server = new WifiConfiguration();
    private WifiConfiguration m_box = new WifiConfiguration();
    private WifiConfiguration m_nopass = new WifiConfiguration();

    public WifiAdmin(Context context) {
        // TODO Auto-generated constructor stub
        //取得WifiManager对象
        m_wifimanger=(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        //取得WifiInfo对象
        m_wifiinfo=m_wifimanger.getConnectionInfo();
        //WPA加密
        m_server.SSID = "\"" + Common.ServerName + "\"";
        m_server.preSharedKey = "\"1234567890\"";
        m_server.hiddenSSID = true;
        m_server.status = WifiConfiguration.Status.ENABLED;
        m_server.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
        m_server.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        m_server.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        m_server.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
        m_server.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
        //wep加密
        m_box.SSID = "\"" + Common.BoxName + "\"";
        m_box.wepKeys[0] = "\"12345\"";
        m_box.hiddenSSID = true;
        m_box.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
        m_box.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        m_box.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        m_box.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
        m_box.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
        m_box.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        m_box.wepTxKeyIndex = 0;
        //无加密
        m_nopass.SSID = "\"" + Common.BoxName + "\"";
        //m_nopass.wepKeys[0] = "\"\"";
        m_nopass.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        m_nopass.wepTxKeyIndex = 0;
    }
    //打开wifi
    public void openWifi(){
        if(!m_wifimanger.isWifiEnabled()){
            m_wifimanger.setWifiEnabled(true);
        }
    }
    //关闭wifi
    public void closeWifi(){
        if(!m_wifimanger.isWifiEnabled()){
            m_wifimanger.setWifiEnabled(false);
        }
    }
    // 检查当前wifi状态
    public int getState() {
        if (m_wifimanger.getWifiState() == 0) {
            if(Common.Debug) Log.i(TAG, "网卡正在关闭");
        } else if (m_wifimanger.getWifiState() == 1) {
            if(Common.Debug) Log.i(TAG, "网卡已经关闭");
        } else if (m_wifimanger.getWifiState() == 2) {
            if(Common.Debug) Log.i(TAG, "网卡正在打开");
        } else if (m_wifimanger.getWifiState() == 3) {
            if(Common.Debug) Log.i(TAG, "网卡已经打开");
        } else {
            if(Common.Debug) Log.i(TAG, "---_---晕......没有获取到状态---_---");
        }
        return m_wifimanger.getWifiState();
    }
    //锁定wifiLock
    public void acquireWifiLock(){
        m_wifilock.acquire();
    }
    //解锁wifiLock
    public void releaseWifiLock(){
        //判断是否锁定
        if(m_wifilock.isHeld()){
            m_wifilock.acquire();
        }
    }
    //创建一个wifiLock
    public void createWifiLock(){
        m_wifilock=m_wifimanger.createWifiLock("test");
    }
    //得到配置好的网络
    public List<WifiConfiguration> getConfiguration(){
        return m_wifi_config;
    }
    //指定配置好的网络进行连接
    public void connetionConfiguration(int index){
        if(index>m_wifi_config.size()){
            return ;
        }
        //连接配置好指定ID的网络
        m_wifimanger.enableNetwork(m_wifi_config.get(index).networkId, true);
    }
    public void startScan(){
        m_wifimanger.startScan();
        //得到扫描结果
        m_wifilist=m_wifimanger.getScanResults();
        if(m_wifilist == null)
        {
            if(Common.Debug) Log.i(TAG,"未搜索到网络!");
        }
        else
        {
            for(int i = 0; i < m_wifilist.size(); i ++)
            {
                if(Common.Debug) Log.i(TAG,"SSID=" + m_wifilist.get(i).SSID);
            }
        }
        //得到配置好的网络连接
        m_wifi_config=m_wifimanger.getConfiguredNetworks();
    }
    //得到网络列表
    public List<ScanResult> getWifiList(){
        return m_wifilist;
    }
    //查看扫描结果
    public StringBuffer lookUpScan(){
        StringBuffer sb=new StringBuffer();
        for(int i=0;i < m_wifilist.size(); i++){
            sb.append("Index_" + new Integer(i + 1).toString() + ":");
            // 将ScanResult信息转换成一个字符串包
            // 其中把包括：BSSID、SSID、capabilities、frequency、level
            sb.append((m_wifilist.get(i)).toString()).append("\n");
        }
        return sb;
    }
    public String getMacAddress(){
        m_wifiinfo=m_wifimanger.getConnectionInfo();
        return (m_wifiinfo==null)?"NULL":m_wifiinfo.getMacAddress();
    }
    public String getBSSID(){
        m_wifiinfo=m_wifimanger.getConnectionInfo();
        return (m_wifiinfo==null)?"NULL":m_wifiinfo.getBSSID();
    }
    public int getIpAddress(){
        m_wifiinfo=m_wifimanger.getConnectionInfo();
        return (m_wifiinfo==null)?0:m_wifiinfo.getIpAddress();
    }
    //得到连接的ID
    public int getNetWordId(){
        m_wifiinfo=m_wifimanger.getConnectionInfo();
        return (m_wifiinfo==null)?0:m_wifiinfo.getNetworkId();
    }
    //得到wifiInfo的所有信息
    public String getWifiInfo(){
        m_wifiinfo=m_wifimanger.getConnectionInfo();
        return (m_wifiinfo==null)?"NULL":m_wifiinfo.toString();
    }
    //获取连接网络情况
    public String getWifiConnectSSID(){
        m_wifiinfo=m_wifimanger.getConnectionInfo();
        String name = (m_wifiinfo==null)?"NULL":m_wifiinfo.getSSID();
        if(name == null || name.length() <= 0) return name;
        if(name.charAt(0) == '"') //已经获取到SSID，去掉头尾
            name = name.replaceAll("\"", "");
        int ip = m_wifiinfo.getIpAddress();
        if(Common.Debug) Log.i(TAG,"IP=" + Commonfunc.IntToIp(ip));
        //如果没有获取到IP地址，也算没有连上
        if(ip == 0) name = "";
        return name;
    }
    //添加一个网络并连接
    public boolean addNetWork(WifiConfiguration configuration){
        int wcgId=m_wifimanger.addNetwork(configuration);
        if(Common.Debug) Log.i(TAG,"wcgId = " + wcgId);
        boolean isok =  m_wifimanger.enableNetwork(wcgId, true);
        if(Common.Debug) Log.i(TAG,"isok = " + isok);

        return isok;
    }
    //断开指定ID的网络
    public void disConnectionWifi(int netId){
        m_wifimanger.disableNetwork(netId);
        m_wifimanger.disconnect();
    }
    //连接到服务器,返回值： -1 -- 没有搜索到服务器 ; 0 -- 连接失败; 1 -- 连接成功
    public int ConnectServer(String name)
    {
        startScan();
        if(m_wifilist == null) return -1;
        for(int i = 0; i < m_wifilist.size(); i ++)
        {
            if(name.equals(m_wifilist.get(i).SSID)) //找到服务器
            {
                if(Common.Debug) Log.i(TAG,"找到服务器网络");
                if(addNetWork(m_server))
                    return 1;
                else
                    return 0;
            }
        }
        return -1;
    }
    //连接box 返回值： -1 -- 没有搜索到Box ; 0 -- 连接失败; 1 -- 连接成功
    public int ConnectBox(String name)
    {
        startScan();
        for(int i = 0; i < m_wifilist.size(); i ++)
        {
            if(name.equals(m_wifilist.get(i).SSID)) //找到服务器
            {
                if(Common.Debug) Log.i(TAG,"找到服务器网络");
                //if(addNetWork(m_box))
                if(addNetWork(m_nopass))
                    return 1;
                else
                    return 0;
            }
        }
        return -1;
    }
    //断开连接
    public void DisConnect()
    {
        m_wifiinfo=m_wifimanger.getConnectionInfo();
        if(m_wifiinfo != null)
            disConnectionWifi(getNetWordId());
    }
}
